import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_bottom.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_electric.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_face.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_identity.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_select.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_social.dart';
import 'package:healthy_station_flutter/ui/home/page_home_login_success.dart';
import 'package:healthy_station_flutter/utils/log_utils.dart';
import 'package:healthy_station_flutter/utils/res_strings.dart';
import 'package:provider/provider.dart';
import '../../entity/develop_resident_entity.dart';
import '../../entity/id_card_entity.dart';
import '../../entity/login_entity.dart';
import '../../entity/social_card_entity.dart';
import '../../network/XHttp.dart';
import '../../network/api.dart';
import '../../provider/provider_app.dart';
import '../../provider/provider_login.dart';
import '../../utils/app_utils.dart';
import '../../utils/constants.dart';
import '../../utils/res_colors.dart';
import '../../utils/res_images.dart';
import '../../utils/screen_adapter.dart';

///
/// @Description
/// @Author WuJianFeng
/// @Date 2024/3/1 10:27
///

class LoginWidget extends StatefulWidget{

  const LoginWidget({super.key});


  @override
  State<StatefulWidget> createState() => _LoginState();

}

class _LoginState extends State<LoginWidget>{
  late MethodChannel mMethodChannel;

  @override
  void initState() {
    super.initState();
    mMethodChannel = const MethodChannel(loginChannel);

  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: Adapt.pt(574),
      height: Adapt.pt(876),
      child: Consumer<LoginProvider>(builder: (context, LoginProvider loginProvider, child) {
        return Stack(
          children: [
            ///背景
            Positioned.fill(
              child: ImageUtils.getImg("login_bg.webp"),
            ),
            ///标题
            Positioned.fill(
              top: Adapt.pt(58),
              child: Align(
                alignment: Alignment.topCenter,
                child: Text(loginTitle(loginProvider.loginType), style: TextStyle(fontSize: Adapt.pt(40), color: color_25364B, fontWeight: FontWeight.bold)),
              ),
            ),

            ///登录内容
            Positioned.fill(
              top: Adapt.pt(96),
              child: Align(
                alignment: Alignment.topCenter,
                child: SizedBox(
                  height: Adapt.pt(604),
                  child: loginContent(loginProvider.loginType,(){
                    loginProvider.setLoginType(loginTypeSuccess);
                  }),
                ),
              ),
            ),

            ///底部按钮
            const Positioned.fill(
              child: Align(
                alignment: Alignment.bottomCenter,
                child: LoginBottomWidget(),
              ),
            ),
          ],
        );
        },
      ),
    );
  }

  String loginTitle(int loginType){
    switch(loginType){

      case loginTypeIdentity :{
        return sLoginIdentity;
      }

      case loginTypeSocial :{
        return sLoginSocial;
      }

      case loginTypeFace :{
        return sLoginFace;
      }

      case loginTypeElectric :{
        return sLoginElectric;
      }

      case loginTypeAccount :{
        return sLoginAccount;
      }

      default :{
        return sLoginType;
      }
    }
  }

  Widget loginContent(int loginType, Function() loginResult){
    switch(loginType){

      case loginTypeIdentity :{

        methodChannel(loginType,loginResult);
        return const LoginIdentityWidget();
      }

      case loginTypeSocial :{
        methodChannel(loginType,loginResult);
        return const LoginSocialWidget();
      }

      case loginTypeFace :{
        methodChannel(loginType,loginResult);
        return const LoginFaceWidget();
      }

      case loginTypeElectric :{
        methodChannel(loginType,loginResult);
        return const LoginElectricWidget();
      }

      case loginTypeAccount :{
        methodChannel(loginType,loginResult);
        return const LoginSelectWidget();
      }

      case loginTypeSuccess :{
        return const LoginSuccessWidget();
      }

      default :{
        return const LoginSelectWidget();
      }
    }
  }

  Future<void> methodChannel(int loginType, Function() loginResult) async {
    switch(loginType){

      case loginTypeIdentity :{
        await getIdentityData(loginResult);
        break;
      }

      case loginTypeSocial :{
        await getSocialData(loginResult);
        break;
      }

      case loginTypeFace :{
        break;
      }

      case loginTypeElectric :{
        break;
      }

      case loginTypeAccount :{
        break;
      }
    }
  }

  Future<void> getIdentityData(Function() loginResult) async {

    /// 调用原生方法并获得返回值
    String returnValue = await mMethodChannel.invokeMethod(loginChannelIdentity,loginChannelIdentity);

    if(returnValue.isEmpty){
      if(LoginProvider().loginType != loginTypeInit){
        if (kDebugMode) {
          LogUtils.d("__getIdentityData-1");
        }
        Future.delayed(const Duration(seconds: 1),(){
          getIdentityData(loginResult);
        });
      }
    }else if(returnValue.startsWith("err")){
      LoginProvider().setLoginType(loginTypeInit);
      Fluttertoast.showToast(msg: returnValue);
    }else{
      IdCardEntity idCardEntity =  IdCardEntity.fromJson(jsonDecode(returnValue));

      if (idCardEntity.idNumber != null && idCardEntity.idNumber!.isNotEmpty){
        Constant.cardNumber = idCardEntity.idNumber!;
      }
      if (idCardEntity.name != null && idCardEntity.name!.isNotEmpty){
        Constant.userName = idCardEntity.name!;
      }
      if (idCardEntity.gender != null && idCardEntity.gender!.isNotEmpty){
        Constant.userGender = idCardEntity.gender!;
      }
      if (idCardEntity.born != null && idCardEntity.born!.isNotEmpty){
        Constant.birthday = idCardEntity.born!;
        Constant.age = AppUtils.calculateAge(idCardEntity.born!.substring(0, 4));
      }
      if (idCardEntity.keyString != null && idCardEntity.keyString!.isNotEmpty){
        Constant.base64Str = idCardEntity.keyString!;
      }
      developResidentInfo(cardTypeIdentity, loginResult);

    }
  }

  Future<void> getSocialData(Function() loginResult) async {

    /// 调用原生方法并获得返回值
    String returnValue = await mMethodChannel.invokeMethod(loginChannelSocial,loginChannelSocial);

    if(returnValue.isEmpty){
      if(LoginProvider().loginType != loginTypeInit){
        LogUtils.d("__getSocialData-1");
        Future.delayed(const Duration(seconds: 1),(){
          getSocialData(loginResult);
        });
      }
    }else if(returnValue.startsWith("err")){
      LoginProvider().setLoginType(loginTypeInit);
      Fluttertoast.showToast(msg: returnValue);
    }else{
      SocialCardEntity socialCardEntity =  SocialCardEntity.fromJson(jsonDecode(returnValue));

      if (socialCardEntity.socialSecurityNumber != null && socialCardEntity.socialSecurityNumber!.isNotEmpty){
        if (socialCardEntity.socialSecurityNumber == sNoPsam){
          LoginProvider().setLoginType(loginTypeInit);
          Fluttertoast.showToast(msg: sNoPsam);
          return;
        }
        Constant.cardNumber = "${socialCardEntity.socialSecurityNumber}";
      }
      Constant.userName = "${socialCardEntity.name}";

      Constant.birthday = "${socialCardEntity.born}";

      Constant.userGender = "${socialCardEntity.gender}";

      if (socialCardEntity.born != null && socialCardEntity.born!.isNotEmpty){
        Constant.age = AppUtils.calculateAge(socialCardEntity.born!.substring(0, 4));
      }

      Constant.socialCardKxx = "${socialCardEntity.socialCardKxx}";

      developResidentInfo(cardTypeSocialCard, loginResult);

    }
  }

  void developResidentInfo(int cardType, Function() loginResult){

    XHttp.getInstance().post<DevelopResidentEntity>(Api.residentInfo, {
      "name": Constant.userName,
      "machineId": AppInfo().machineId,
      "brxz": AppUtils.getBrxz(Constant.cardType),
      "socialCardKxx": Constant.socialCardKxx,
      "cardNo": Constant.cardNumber
    }).then((value){
      Constant.userId = "${value.data?.userId}";
      if (cardType == cardTypeMedicalInsurance){
        Constant.cardNumber = "${value.data?.certifcateNo}";
        Constant.userName = "${value.data?.name}";
        Constant.birthday = "${value.data?.birth}";
        Constant.userGender = AppUtils.getUserSex("${value.data?.sex}");
        if (value.data?.birth != null && value.data!.birth!.isNotEmpty){
          Constant.age = AppUtils.calculateAge(value.data!.birth!.replaceAll("-","").substring(0, 4));
        }
      }
      login(cardType, loginResult);
      LogUtils.d("__developResident-value  code:${value.code}  message:${value.message}  data:${value.data}");
    }).catchError((err) {
      // DO SOMETHING
      LogUtils.d("__developResident-err $err");
    });

  }

  void login(int cardType, Function() loginResult){
    Constant.cardType = cardType;
    XHttp.getInstance().post<LoginEntity>(Api.login, {
      "account": Constant.cardNumber,
      "loginModel": AppUtils.getLoginModel(cardType),
      "usr": "resident",
      "ccd": "KHDLX-APP",
      "machineId": AppInfo().machineId
    }).then((value){
      Constant.token = "${value.data?.token}";
      loginResult();
      // widget.loginProvider.setLoginType(loginTypeSuccess);
    }).catchError((err) {
      // DO SOMETHING
      LogUtils.d("__login-err $err");
    });
  }

}

